<template>
  <div>
    <h3 style="margin-bottom:20px">{{ id ? '编辑' : '创建' }}分类</h3>
    <el-form label-width="80px" :model="model" @submit.native.prevent="save">
      <el-form-item label="上级分类">
        <template>
          <el-select v-model="model.parent" clearable placeholder="请选择">
            <el-option v-for="item in options" :key="item._id" :label="item.name" :value="item._id">
            </el-option>
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="分类名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">{{
          id ? '保存变更' : '立即创建'
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: ['id'],
  data () {
    return {
      model: {},
      options: []
    }
  },
  methods: {
    async save () {
      if (this.id) {
        await this.$http.put(`/common/category/${this.id}`, this.model)
      } else {
        await this.$http.post('/common/category', this.model)
      }
      this.$router.push('/category/list')
      this.$message({
        type: 'success',
        message: '创建成功'
      })
    },
    async fetch () {
      const res = await this.$http.get(`/common/category/${this.id}`)
      this.model = res.data
    },
    async fetchParent () {
      const res = await this.$http.get('/common/category')
      this.options = res.data
    }
  },
  created () {
    this.id && this.fetch()
    this.fetchParent()
  }
}
</script>

<style></style>
